package cn.ecut.reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

/**
 * @Author ruanxin
 */
//反射获取注解
public class Test09 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("cn.ecut.reflection.workman");

        //通过反射获取注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获取value的值
        Tableman tableman = (Tableman) c1.getAnnotation(Tableman.class);
        System.out.println(tableman.value());

        //获得类指定的注解
        Field f = c1.getDeclaredField("name");
        Fieldman annotation = f.getAnnotation(Fieldman.class);
        System.out.println(annotation.columName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());

    }

}

@Tableman("db_workman")
class workman {

    @Fieldman(columName = "db_id", type = "int", length = 10)
    private int id;
    @Fieldman(columName = "db_age", type = "int", length = 10)
    private int age;
    @Fieldman(columName = "db_name", type = "varchar", length = 20)
    private String name;

    @Override
    public String toString() {
        return "workman{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public workman() {
    }

    public workman(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

//类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tableman {
    String value();
}

//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldman {
    String columName();

    String type();

    int length();
}
